package com.tavenli.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.util.logging.resources.logging;

import com.tavenli.entity.F18Device;
import com.tavenli.entity.PersonEntity;
import com.tavenli.model.PageData;
import com.tavenli.services.UPersonService;
import com.tavenli.utils.PageNavUtil;
import com.tavenli.utils.ValidatorUtil;

@Controller
@RequestMapping("/per")
public class UPersonController {
	private static Logger logger = LoggerFactory.getLogger(UCenterController.class);
	
	@Autowired
	private UPersonService uPersonService;
	
	@RequestMapping("/pers")
	public String devicesList(Model model,Integer page,String userName) {
		page = page== null ? 1 : page<1 ? 1 : page;
		int pageSize = 10;
		PageData<PersonEntity> pageData = this.uPersonService.getPersonList(page, pageSize, userName);
		model.addAttribute("pageData", pageData);
		return "admin/pers_list";
	}
	
	@RequestMapping("/persEdit")
	public String persEdit(Model model,int id) {
		PersonEntity personEntity = this.uPersonService.getPersonById(id);
		model.addAttribute("personEntity", personEntity);
		return "admin/pers_edit";
	}
	
	
	
	@RequestMapping(value = "/savePers", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> savePers(Model model,PersonEntity personEntity) {
		boolean resultStatus = false;
		Map<String, Object> resMap = new HashMap<String, Object>();
		
		String personName = personEntity.getPersonName();
		if(personEntity==null || StringUtils.isBlank(personName)){
			resultStatus = false;
			resMap.put("errorMsg", "姓名不能为空");
			resMap.put("resultStatus", resultStatus);
			return resMap;
		}
		//过滤非法字符
		personName = ValidatorUtil.filterUnSafeChar(personName).trim();
		if (null!=personName&&personEntity.getId()>0) {
			personEntity=uPersonService.getPersonById(personEntity.getId());
		}
		personEntity.setPersonName(personName);
		try {
			personEntity = this.uPersonService.saveAndSendToDev(personEntity);
			if (null!=personEntity) {
				resultStatus=true;
			}
		} catch (Exception e) {
			logger.error("保存人员信息出错");
		}
		resMap.put("resultStatus", resultStatus);
		return resMap;
	}
	
}
